package com.shell.scheduler.job.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.shell.bee.persistence.annotation.Pagination;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.bee.persistence.service.impl.PersistentServiceImpl;
import com.shell.scheduler.SchedulerManager;
import com.shell.scheduler.job.po.SchdJob;
import com.shell.scheduler.job.service.ScheJobService;

import tk.mybatis.mapper.entity.Example;

@Service("scheJobService")
public class ScheJobServiceImpl extends PersistentServiceImpl<SchdJob> implements ScheJobService {
	public boolean add(SchdJob scheJob) {
		int scount = save(scheJob);
		String state = scheJob.getJobState();
		switch (state) {
		case "E":
			SchedulerManager.addJob(scheJob);
			break;
		case "U":
			SchedulerManager.addJob(scheJob);
			SchedulerManager.pauseJob(scheJob.getJobCode());
			break;
		}
		return scount > 0;
	}

	public boolean update(SchdJob scheJob) {
		int ucount = updateAll(scheJob);
		SchedulerManager.addJob(scheJob);
		return ucount > 0;
	}

	public void trigger(String jobCode, String traceId, String workDate) {
		Map<String, String> context = null;
		if ((workDate != null) && (!"".equals(workDate))) {
			context = new HashMap<String, String>();
			context.put("traceId", traceId);
			context.put("workDate", workDate);
		}
		SchedulerManager.triggerJob(jobCode, context);
	}

	public void pause(String jobCode) {
		SchedulerManager.pauseJob(jobCode);
	}

	public void resume(String jobCode) {
		SchedulerManager.resumeJob(jobCode);
	}

	public boolean delete(SchdJob scheJob) {
		scheJob.setJobState("D");
		int dcount = deleteEntity(scheJob);
		SchedulerManager.deleteJob(scheJob.getJobCode());
		return dcount > 0;
	}

	public List<SchdJob> findEnabledJobs() {
		Example example = new Example(SchdJob.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andNotEqualTo("jobState", "U");
		return selectByExample(example);
	}

	@Pagination
	public List<SchdJob> selectAllJobs(PageLimit limit, SchdJob scheJob) {
		return selectAll();
	}

	public boolean checkJobCode(String jobCode) {
		SchdJob scheJob = (SchdJob) selectByKey(jobCode);
		return scheJob != null;
	}
}